package com.ruoyi.business.utils;

import com.aspose.cells.*;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;

public class Excel2PdfUtil {

    @Value("${fontFolder}")
    private static String fontFolder;

    @Value("${licenseFile}")
    private static String licenseFile;


    /**
     * excel文件转换为PDF文件
     * @param Address 需要转化的Excel文件地址，
     * @param outputPath 转换后的文件地址
     */
    public static String excel2pdf(String Address,String outputPath,String fileName) {
        if (!getLicense()) {   // 验证License 若不验证则转化出的pdf文档会有水印产生
            return null;
        }
        try {
            FileWriter writer = new FileWriter(outputPath + fileName);
            writer.close();
            File pdfFile = new File(outputPath + fileName); // 输出路径


            IndividualFontConfigs configs = new IndividualFontConfigs();
            configs.setFontFolder(fontFolder, true);
            LoadOptions loadOptions  = new LoadOptions();
            loadOptions.setFontConfigs(configs);


            FileInputStream excelstream = new FileInputStream(Address);
            Workbook wb = new Workbook(excelstream,loadOptions);// excel路径，这里是先把数据放进缓存表里，然后把缓存表转化成PDF
            FileOutputStream fileOS = new FileOutputStream(pdfFile);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);//参数true把内容放在一张PDF页面上；
            wb.save(fileOS, pdfSaveOptions);
            fileOS.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    //获取认证，去除水印
    public static boolean getLicense() {
        boolean result = false;
        try {
//            InputStream is = Excel2PdfUtil.class.getClassLoader().getResourceAsStream(licenseFile);//这个文件应该是类似于密码验证(证书？)，用于获得去除水印的权限
            InputStream is = Excel2PdfUtil.class.getClassLoader().getResourceAsStream("ruoyi-admin/src/main/resources/license.xml");//这个文件应该是类似于密码验证(证书？)，用于获得去除水印的权限
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
